# -*- coding:utf-8 -*-
from django.utils.deprecation import MiddlewareMixin
from users.models import Records, BusinessPermission
import json
from ElevatorAdmin.settings import AES_KEY
from utils.cryptor import AESCrypto
from utils.has_permission import has_permission


def set_record(request):
    url_path = request.path

    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[-1].strip()
    else:
        ip = request.META.get('REMOTE_ADDR')

    method = request.method
    if method in ['POST', 'DELETE', 'PUT']:
        parameters = request.body
    elif method in ['GET']:
        parameters = dict(zip(request.GET.keys(), request.GET.values()))
    else:
        parameters = u''
    if request.FILES.keys():
        parameters = u'文件上传，此项参数不做记录'
    parameters = json.dumps(parameters) if parameters else u''
    user_agent = request.META.get('HTTP_USER_AGENT', None)
    user = request.user
    b = request.user.is_authenticated()
    if b:
        user_id = user.id
        is_anonymous = False
    else:
        user_id = 0
        is_anonymous = True

    try:
        Records.objects.create(user_agent=user_agent, path=url_path, ip=ip, user_id=user_id, is_anonymous=is_anonymous,
                               parameters=parameters, method=method)
    except Exception as e:
        print e


def get_permission(text):
    try:
        ao = AESCrypto(AES_KEY)
        p = ao.decrypt(text=text).split(",")
    except Exception as e:
        p = []
    return p


class PermissionMiddleware(MiddlewareMixin):

    PERMISSION_METHODS = ['post', 'put', 'delete']

    PERMISSION_EXCEPT_URL = [
        '/api/v1/user/register/',
        '/api/v1/user/login/',
        '/api/v1/user/redirect/',
        '/api/v1/user/logout/',
        '/api/v1/user/app/login/',
        '/api/v1/user/app/logout/',
        '/api/v1/maintain/task/pdf/',
        "/api/v1/user/picture/",
        "/api/v1/user/address/",
        "/api/v1/user/hour/price/",
    ]

    COMPANY_EXCEPT_URL = [
        "/api/v1/user/submit/"
    ]

    # ADMIN_EXCEPT_URL = [
    #     '/api/v1/user/company/',
    #     '/api/v1/user/auth/',
    #     '/api/v1/user/bind/',
    #     '/api/v1/basic/elevator/',
    #     '/api/v1/maintain/contract/',
    #     '/api/v1/maintain/task/manu/submit/'
    # ]

    def process_request(self, request):

        url_path = request.path
        setattr(request, 'has_permission', True)
        if url_path.startswith('/wx-elevator/'):
            return

        if request.user.is_authenticated() and request.user == u"admin":
            return

        if url_path.startswith('/v1/'):
            return
        # try:
        #     set_record(request)
        # except Exception as e:
        #     print e

        if url_path.startswith("/api/v1/utils/upload/") and request.user.is_authenticated():
            return

        if url_path.startswith("/api/v1/user/auth/") and request.user.is_authenticated():
            return

        if url_path.startswith('/api/v1/rescue/') and url_path.split("/")[3] != "app":
            return
        if url_path.startswith('/Get'):
            return
        if url_path == '/es.json':
            return
        if url_path == '/ef.json':
            return
        if url_path in PermissionMiddleware.PERMISSION_EXCEPT_URL:
            return
        if url_path in PermissionMiddleware.COMPANY_EXCEPT_URL:
            return
        if not hasattr(request, "user") or not request.user.is_authenticated:
            setattr(request, 'has_permission', False)
            return

        # if request.user.role == 0 and request.method == "PUT" and url_path.startswith(PermissionMiddleware.ADMIN_EXCEPT_URL[1]):
        #     return
        #
        # if request.user.role == 0 and request.method == "DELETE" and url_path.startswith(PermissionMiddleware.ADMIN_EXCEPT_URL[4]):
        #     return
        #
        # if request.user.role == 0 and request.method == "DELETE" and url_path.startswith(PermissionMiddleware.ADMIN_EXCEPT_URL[3]):
        #     return
        #
        # if request.user.role != 0 and request.method == "DELETE" and url_path.startswith(PermissionMiddleware.ADMIN_EXCEPT_URL[3]):
        #     setattr(request, 'has_permission', False)
        #     return

        # if request.user.role == 0 and request.method.lower() in PermissionMiddleware.PERMISSION_METHODS:
        #     setattr(request, 'has_permission', False)
        #     if url_path.startswith(PermissionMiddleware.ADMIN_EXCEPT_URL[0]) or url_path.startswith(PermissionMiddleware.ADMIN_EXCEPT_URL[2]) or url_path.startswith(PermissionMiddleware.ADMIN_EXCEPT_URL[5]):
        #         setattr(request, 'has_permission', True)
        #     return

        terminal_type = url_path.split('/')[4]
        if request.user.role in [10] and terminal_type != 'app':
            setattr(request, 'has_permission', False)
            return

        if request.user.role in [0, 20] and terminal_type == 'app':
            setattr(request, 'has_permission', False)
            return

        if terminal_type == 'app':
            user = request.user
            session = request.session.get('session', u"")
            if user.session != session:
                setattr(request, 'has_permission', False)
            return
        # 请求过来时查询权限
        permissions = get_permission(request.session['ep'])
        if not permissions:
            setattr(request, 'has_permission', False)
            return
        elif permissions == ["0"]:
            return
        method = request.method.lower()
        b = has_permission(url_path, permissions, method, request.user.role, request.body, request.GET)
        if not b:
            setattr(request, 'has_permission', False)
            return


        return

    # 每次返回时更新权限
    # def process_response(self, request, response):
    #     b = request.user.is_authenticated()
    #     print "request.user: %s " % request.user
    #     if b:
    #         permissions = request.user.permissions()
    #         ao = AESCrypto(AES_KEY)
    #         request.session['ep'] = ao.encrypt(",".join(permissions))
    #     return response





